#!/bin/bash -eu
# Copyright 2020 Timothy Trippel
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

: ${KCOV_PATH:=/src/kcov/build/src}
: ${LOGS_PATH:=logs}
: ${OUT_PATH:=out}

echo "Tracing LINE COVERAGE with kcov ..."
rm -rf bin build model *.vcd
source $SCRIPTS/set_hwf_isa.sh
CPPFLAGS="-g" \
  make -j 2 \
  TB_CXXFLAGS="$TB_CXXFLAGS" \
  DISABLE_VCD_TRACING=1

# Create output dirs
KCOV_ROOT=$LOGS_PATH/kcov
KCOV_TMP_CURR=$KCOV_ROOT/tmp_curr
KCOV_TMP_MERGE_1=$KCOV_ROOT/tmp_merge_1
KCOV_TMP_MERGE_2=$KCOV_ROOT/tmp_merge_2
rm -rf $KCOV_ROOT
mkdir -p $KCOV_ROOT
chmod 777 $KCOV_ROOT
mkdir -p $KCOV_TMP_CURR
mkdir -p $KCOV_TMP_MERGE_1
mkdir -p $KCOV_TMP_MERGE_2

# Trace coverage of each test case
TEST_CASE_NUM=0
# TODO(ttrippel): make sure we are processing seed files in the order they were
# created. Right now we are relying on the alphabetical ordering of the seed
# file names which all start with a unique ID number for AFL.
for TEST_CASE in $OUT_PATH/*/queue/*; do

  # run kcov
  echo -n "    Tracing test: $(basename "$TEST_CASE") ... "
  $KCOV_PATH/kcov $KCOV_TMP_CURR bin/$TOPLEVEL <"$TEST_CASE" >/dev/null
  echo "Done."

  # merge all prior tracing results
  echo -n "    Merging $((TEST_CASE_NUM + 1)) coverage traces ... "
  # select which tmp directory to output too: even -> 2, odd -> 1
  if [ $((TEST_CASE_NUM % 2)) -eq 0 ]; then
    CURR_MERGE_OUT=$KCOV_TMP_MERGE_2
    PRIOR_MERGE_OUT=$KCOV_TMP_MERGE_1
  else
    CURR_MERGE_OUT=$KCOV_TMP_MERGE_1
    PRIOR_MERGE_OUT=$KCOV_TMP_MERGE_2
  fi
  # merge all existing coverage traces
  $KCOV_PATH/kcov --merge $CURR_MERGE_OUT $PRIOR_MERGE_OUT $KCOV_TMP_CURR

  # move out the JSON results (this is what we will save for plotting)
  # results from curr test case
  mv $KCOV_TMP_CURR/$TOPLEVEL.*/coverage.json $KCOV_ROOT/kcov_$TEST_CASE_NUM.json
  chmod 666 $KCOV_ROOT/kcov_$TEST_CASE_NUM.json
  # results from merged test cases
  mv $CURR_MERGE_OUT/kcov-merged/coverage.json \
    $KCOV_ROOT/kcov_cum_${TEST_CASE_NUM}.json
  chmod 666 $KCOV_ROOT/kcov_cum_${TEST_CASE_NUM}.json
  echo "Done."

  # Wipe the prior merge output dir and tmp_curr dir
  rm -rf $PRIOR_MERGE_OUT/*
  rm -rf $KCOV_TMP_CURR/*

  # increment test number and update previous output dir
  TEST_CASE_NUM=$((TEST_CASE_NUM + 1))
done
rm -rf $KCOV_TMP_CURR
rm -rf $KCOV_TMP_MERGE_1
rm -rf $KCOV_TMP_MERGE_2
echo "Done."
echo "Traced LINE COVERAGE from $TEST_CASE_NUM test cases."
